﻿using System;
using System.IO;
using System.Net;
using System.Globalization;
using HAVNet.Core;
using System.Net.Sockets;


namespace GPSServer
{
    class WebUpdater
    {
        public static void simpleRequest (string imei, double lat, double lon, double vel)
        {
            using (WebClient wc = new WebClient())
            {
                wc.Proxy.Credentials = new NetworkCredential("avarela", "gomagoma");

                string uri = "http://televoyeur.com/updater.aspx?modo=0&tiempo=0&descr=[DESCR]&lat=[LAT]&lon=[LON]&vel=[VEL]";

                uri = uri.Replace("[DESCR]", imei);
                uri = uri.Replace("[LAT]", lat.ToString(CultureInfo.InvariantCulture.NumberFormat));
                uri = uri.Replace("[LON]", lon.ToString(CultureInfo.InvariantCulture.NumberFormat));
                uri = uri.Replace("[VEL]", vel.ToString(CultureInfo.InvariantCulture.NumberFormat));

                using (StreamReader sr = new StreamReader(wc.OpenRead(uri)))
                {
                    TSConsole.mostrarln(sr.ReadToEnd(), ConsoleColor.Cyan);
                    sr.Close();
                }
            }
        }

        public static string jsonRequest (string json)
        {
            string ret = "";

            try
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Proxy.Credentials = new NetworkCredential("avarela", "gomagoma");

                    string uri = "http://televoyeur.com/updater.aspx?modo=1&text=[JSON]";

                    uri = uri.Replace("[JSON]", json);

                    using (StreamReader sr = new StreamReader(wc.OpenRead(uri)))
                    {
                        ret = sr.ReadToEnd();
                        sr.Close();
                    }
                }
            }
            catch (Exception exx)
            { 
                TSConsole.mostrarln("Error en jsonRequest: " + exx.Message, ConsoleColor.Red);
            }

            return ret;
        }

        public static string jsonRequestPost (string json)
        {
            string ret = "";

            try
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    string data = "modo=1&text=" + json;
                    ret = wc.UploadString("http://televoyeur.com/updater.aspx", "POST", data);
                }
            }
            catch (Exception exx)
            {
                TSConsole.mostrarln("Error en jsonRequestPost: " + exx.Message, ConsoleColor.Red);
            }

            return ret;
        }
    }
}
